var inbox_reload_jcache = false;
var outbox_reload_jcache = false;
var buttonSelected = 'tab_inbox';

function onClickButtonMes(tab){
	document.getElementById('tab_inbox').className = '';
	document.getElementById('tab_outbox').className = '';
	document.getElementById('tab_compose').className = '';
	document.getElementById('bound_search_me').style.display = '';	
	if(tab){		
		 document.getElementById('tab_' + tab).className = "selected";
		 buttonSelected = 'tab_' + tab;
	}
}

function onMoveOverButtonMes(thisObj){
	var tabs = ['tab_inbox', 'tab_outbox', 'tab_compose'];
	var len = tabs.length;
	for (var i = 0 ; i < len; i ++) {
		var element = document.getElementById(tabs[i]);
		if (element && element.className != "selected") {
			element.className = "";
		}
	}
	thisObj.className = "selected";
}

function onMoveOutButtonMes(){
	document.getElementById('tab_inbox').className = '';
	document.getElementById('tab_outbox').className = '';
	document.getElementById('tab_compose').className = '';	
	document.getElementById(buttonSelected).className = "selected";
}

function loadInboxMes(search_text){
	back_list_mes('');	
	jQuery.jCache.maxSize = 10;
	
	var cache_key = WEB_DIR+"ajax.php?act=personal&code=show_mes_inbox"+url_archive+"&search_text="+search_text + "&ref=" + comeFrom;
	if (jQuery.jCache.hasItem(cache_key) && !inbox_reload_jcache){
		var val = jQuery.jCache.getItem(cache_key);
		if(!isNaN(val))
		{
			fn_show_mes_detail(val,0,'inbox');
		}
		else
		{
			document.getElementById('mess_content').innerHTML = val;
			DoWhenBoxReady();
		}
	}
	else{		
			jQuery.get(cache_key, function(data){
				if(!isNaN(data))
				{
					fn_show_mes_detail(data,0,'inbox');
				}
				else
				{
					document.getElementById('mess_content').innerHTML = data;				
					jQuery.jCache.setItem(cache_key, data);	
					DoWhenBoxReady();
				}
			});		
	}
	
	
	inbox_reload_jcache = false;	
}

function DoWhenBoxReady()
{
	jQuery('.clickable').hover(
		function(){
			jQuery("#a_" + this.lang).css({'color':'#FF6600'});
		},
		function(){
			jQuery("#a_" + this.lang).css({'color':'#034B8A'});
		}
	).click(function(){
		jQuery("#a_" + this.lang).click();
		window.location = jQuery("#a_" + this.lang).attr('href');
	});	
	
	jQuery('#select_all').click(function(){
		jQuery('.rowbox').each(function()
		{
			this.checked = true;
		})
	});
	
	jQuery('#select_read').click(function(){
		jQuery('.rowbox').each(function()
		{
			if(!jQuery(this).hasClass('unreadMessage'))
			{
				this.checked = true;
			}
			else
			{
				this.checked = false;
			}
		})
	});
	
	jQuery('#select_unchecked').click(function(){
		jQuery('.rowbox').each(function()
		{
			if(this.checked)
			{
				this.checked = false;
			}
			else
			{
				this.checked = true;
			}
		})
	});
	
}

function loadOutboxMes(search_text){	
	back_list_mes('');	
	jQuery.jCache.maxSize = 10;
	var cache_key = WEB_DIR+"ajax.php?act=personal&code=show_mes_outbox"+url_archive+"&search_text="+search_text;
	if (jQuery.jCache.hasItem(cache_key) && !outbox_reload_jcache){
		document.getElementById('mess_content').innerHTML = jQuery.jCache.getItem(cache_key);
		DoWhenBoxReady();
	}
	else{		
			jQuery.get(cache_key, function(data){
				document.getElementById('mess_content').innerHTML = data;				
				jQuery.jCache.setItem(cache_key, data);		
				DoWhenBoxReady();
			});		
	}
	
	outbox_reload_jcache = false;	
}


function delMessage(mt_id,del_all,type){
	var is_archive = (url_archive) ? 1 : 0;
	if(mt_id==0 && del_all=="true"){// xoa nhieu item
		
		var form_name = "message";
		var frm_name = eval("document."+form_name);
		var str_ids = "";
		
		for (var i = 0; i < frm_name.elements.length; i++){
			if (frm_name.elements[i].type == "checkbox" && frm_name.elements[i].checked) {			
				str_ids += (str_ids?",":"")+frm_name.elements[i].value;
			}
		}
		if(str_ids!=""){
			if(confirm("Bạn có muốn xóa những tin nhắn đã chọn không?")){
				jQuery.ajax({
					'url': WEB_DIR+'ajax.php',
					'data': {
						'act':'personal', 
						'code':'delmess',
						'is_archive':is_archive,
						'mt_ids': str_ids
						},
					'type': 'POST',
					'success': function(data){
						if(data=="success"){							
							if(type=="inbox"){
								 inbox_reload_jcache = true;
								 window.location.hash = '#inbox';
								 loadInboxMes('');
								 
								var num_mess = parseInt(jQuery('#num_message').html());
								
								jQuery('.rowbox').each(function()
								{
									if(this.checked&&jQuery(this).hasClass('unreadMessage')&&(num_mess > 0))
									{
										num_mess--;
									}
								});
								
								if(num_mess > 0)
								{
									jQuery('#num_message').html(num_mess);
									
								}
								else
								{
									jQuery('#alert-msg').css({display:'none'});
								}
							}
							else{
								outbox_reload_jcache = true;
								window.location.hash = '#outbox';
								loadOutboxMes('');								
							}
						}
						else{
							alert("Không xóa được tin nhắn");
							return false;
						}
					}
				});	
			}
			else{
				return false;
			}
		}
	}
	else{// xoa 1 item
		if(confirm("Bạn có muốn xóa tin nhắn này không?")){
			jQuery.ajax({
				'url': WEB_DIR+'ajax.php',
				'data': {
					'act':'personal', 
					'code':'delmess',
					'is_archive':is_archive,
					'mt_id': mt_id
					},
				'type': 'POST',
				'success': function(data){
					if(data=="unsuccess"){
						alert("Không xóa được tin nhắn");
						return false;
					}
					else{
						if(type=="inbox"){
							 inbox_reload_jcache = true;
							 back_list_mes('');
							 window.location.hash = '#inbox';
							 loadInboxMes('');
							 var num_mess = parseInt(jQuery('#num_message').html());
								
							jQuery('.rowbox').each(function()
							{
								if((this.value==mt_id)&&jQuery(this).hasClass('unreadMessage')&&(num_mess > 0))
								{
									num_mess--;
								}
							});
							
							if(num_mess > 0)
							{
								jQuery('#num_message').html(num_mess);
								
							}
							else
							{
								jQuery('#alert-msg').css({display:'none'});
							}
						}
						else if(type=="sent"){
							outbox_reload_jcache = true;
							back_list_mes('');
							window.location.hash = '#outbox';
							loadOutboxMes('');
						}
						else
						{
							
						}
					}
				}
			});			
		}
		else{
			return false;
		}
	}
}

function fn_show_mes_detail(mes_id,mt_read,boxType){
	
	jQuery.jCache.maxSize = 10;
	var cache_key = WEB_DIR+"ajax.php?act=personal&code=show_detail_mess&mt_id="+mes_id+url_archive + '&boxType=' + boxType;
	var divid = "#list_mes_detail";
	if (jQuery.jCache.hasItem(cache_key) && !detail_reload_jcache){
		jQuery(divid).html(jQuery.jCache.getItem(cache_key));			
	}
	else{
		jQuery.get(cache_key, function(data){
			jQuery(divid).html(data);
			jQuery.jCache.setItem(cache_key, data);
		});
	}
	detail_reload_jcache = false;
	
	// Nếu tin nhắn đang xét là tin chưa đọc
	//alert(mt_read);
	if(mt_read == 0)
	{
		var num_mess = parseInt(jQuery('#num_message').html());
		//alert(num_mess);
		if(num_mess > 0) num_mess--;
		if(num_mess > 0)
		{
			jQuery('#num_message').html(num_mess);
			
		}
		else
		{
			jQuery('#alert-msg').css({display:'none'});
		}
	}

	jQuery("#list_mes_detail").css({display:""});		
	jQuery("#mess_content").css({display:"none"});
	jQuery("#compose_mess").css({display:"none"});
}


function fn_show_mes_detailIE(mes_id){
	
	var ie = ((jQuery.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) || (jQuery.browser.msie && /MSIE 7.0/.test(navigator.userAgent)) || (jQuery.browser.msie && /MSIE 8.0/.test(navigator.userAgent)));	
	if(ie){	
		jQuery.jCache.maxSize = 10;
		var cache_key = WEB_DIR+"ajax.php?act=personal&code=show_detail_mess&mt_id="+mes_id+url_archive;
		var divid = "#list_mes_detail";
		if (jQuery.jCache.hasItem(cache_key)){
			jQuery(divid).html(jQuery.jCache.getItem(cache_key));			
		}
		else{
			jQuery.get(cache_key, function(data){
				jQuery(divid).html(data);
				jQuery.jCache.setItem(cache_key, data);
			});
		}
		jQuery("#list_mes_detail").css({display:""});		
		jQuery("#mess_content").css({display:"none"});
		jQuery("#compose_mess").css({display:"none"});
	}
}

function back_list_mes(type){
	if(type=="inbox"){
		 inbox_reload_jcache = true;
		loadInboxMes('');	
	}
	else if(type=="outbox"){
		outbox_reload_jcache = true;
		loadOutboxMes('');
	}
	jQuery("#list_mes_detail").css({display:"none"});	
	jQuery("#mess_content").css({display:"block"});	
	jQuery("#compose_mess").css({display:"none"});	
}

function showMesCompose(){	
	jQuery("#list_mes_detail").css({display:"none"});	
	jQuery("#mess_content").css({display:"none"});
	jQuery("#bound_search_me").css({display:"none"});
	jQuery("#compose_mess").css({display:''});	
	jQuery("#mess_success").css({display:"none"});	
	document.getElementById('user_name').value = '';
	document.getElementById('title_pm').value = '';
	document.getElementById('content_pm').value = '';
}

function area_set_auto_resize(eid, rows){
	jQuery(eid).keypress(function(e){
			if(this.style.height)
			this.style.height='';
			
			if(rows<2)
			rows =2;
			
			this.rows = rows-1;
			while(this.scrollHeight > this.clientHeight){
				this.rows +=1;
			}
			
			this.rows +=1;
	});
}

function check_send_mess(type){
	
	var is_save = 1;
	
	var content_pm = getValueId('content_pm');
	var title_pm = getValueId('title_pm');	
	var ref_id = getValueId('ref_id');	
	var user_name = getValueId('textareaUserName')? getValueId('textareaUserName'): getValueId('user_name');
	if(user_name==""){
		document.getElementById('mess_success').style.display = '';
		document.getElementById('mess_success').innerHTML = 'Tài khoản thành viên nhận không hợp lệ';	
		document.getElementById('user_name').focus();
	}
	else if(title_pm==""){
		document.getElementById('mess_success').style.display = '';
		document.getElementById('mess_success').innerHTML = 'Tiêu đề tin nhắn không hợp lệ';
		document.getElementById('title_pm').focus();
	}
	else if(content_pm==""){
		document.getElementById('mess_success').style.display = '';
		document.getElementById('mess_success').innerHTML = 'Nội dung tin nhắn không hợp lệ';	
		document.getElementById('content_pm').focus();
	}
	else{	
		if(getValueId('is_save','checked')){
			var is_save = 1;	
		}
		
		jQuery.ajax({
			'url': WEB_DIR+'ajax.php',
			'data': {
				'act':'personal', 
				'code':'send_mess',
				'user_name':user_name,
				'ref_id':ref_id,
				'title_pm':title_pm,
				'content_pm':content_pm,
				'is_save':is_save
				},
			'type': 'POST',
			'success': function(data){
				if(data=="not_login"){
					document.getElementById('mess_success').style.display = '';
					document.getElementById('mess_success').innerHTML = 'Bạn phải đăng nhập mới gửi được tin nhắn';
				}
				else if(data=="your_self"){
					document.getElementById('mess_success').style.display = '';
					document.getElementById('mess_success').innerHTML = 'Bạn không được gửi tin nhắn cho chính bạn';
				}
				else if(data=="over_limit"){
					document.getElementById('mess_success').style.display = '';
					document.getElementById('mess_success').innerHTML = 'Vượt quá 5 thành viên cho phép gửi cùng lúc';
				}					
				else if(data=="unsuccess"){
					document.getElementById('mess_success').style.display = '';
					document.getElementById('mess_success').innerHTML = 'Không gửi được tin nhắn. Hãy kiểm tra lại các thông tin';
				}
				else{ // gui tin nhan thanh cong
					document.getElementById('user_name').value="";						
					document.getElementById('title_pm').value="";
					//document.getElementById('content_pm').value="";
					document.getElementById('mess_success').style.display = '';	
					document.getElementById('mess_success').innerHTML = data;	
					setTimeout(function(){
										document.getElementById('mess_success').style.display = 'none';
										document.getElementById('bound_search_me').style.display = '';
										inbox_reload_jcache = true;
										loadInboxMes('');
										document.getElementById('tab_compose').className = '';
										document.getElementById('tab_inbox').className = 'selected';	
										buttonSelected = 'tab_inbox';
										window.location.hash = '#inbox';
									}, 2000); 
				}
				outbox_reload_jcache = true;
			}
		});
	}
		
}

function mesForwardReply(mt_id,type){
	showMesCompose();	
	document.getElementById('list_mes_detail').style.display = 'none';	
	document.getElementById('tab_inbox').className = '';
	document.getElementById('tab_outbox').className = '';		
	document.getElementById('tab_compose').className = 'selected';	
	buttonSelected = 'tab_compose';
	jQuery.post(WEB_DIR+"ajax.php?act=personal&code="+type+"&mt_id="+mt_id+url_archive,
		{mt_id : mt_id},
		function(json){	
			document.getElementById('user_name').value = json['receiver'];
			document.getElementById('title_pm').value = json['title'];
			if(type == 'rpMess'){
				//document.getElementById('content_pm').value = '';	
				document.getElementById('content_pm').focus();
				document.getElementById('content_pm').value = '\n\n'+json['content'];
			}
			else{
				document.getElementById('user_name').focus();
				document.getElementById('content_pm').value = '\n\n'+json['content'];
			}
		}
		,"json"
	);
}

function selecte_all_checkbox(form_name){
	var frm_name = eval("document."+form_name);
	for (var i = 0; i < frm_name.elements.length; i++) {
		if (frm_name.elements[i].type == "checkbox") {
			frm_name.elements[i].checked = (frm_name.elements[i].checked==true)?false:true;
			
			try{
				document.getElementById('all_check_box').checked = (frm_name.elements[i].checked==true)?true:false;
			}
			catch (e){
							//Do nothing?
			}
		}
	}
}

function search_mes(obj){
	var search_text  = getValueId('search_text');		
	if(buttonSelected == 'tab_inbox'){
		loadInboxMes(search_text);
	}
	else if(buttonSelected == 'tab_outbox'){
		loadOutboxMes(search_text);
	}
}